#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>

int main (int argc,char** argv)
{
    if (argc != 3)
    {
        printf("wrong cli argc!\n");
        return -1;
    }
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if ( sockfd == -1 )
    {
        perror("socket");
        return -1;
    }
    struct hostent* h;
    if ( (h = gethostbyname(argv[1])) == 0 )
    {
        printf("get host name failed!\n");
        close(sockfd);
        return -1;
    }
    struct sockaddr_in servaddr;
    memset(&servaddr,0,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(atoi(argv[2]));
    memcpy(&servaddr.sin_addr,h->h_addr,h->h_length);
    if (connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) != 0)
    {
        perror("connect");
        close(sockfd);
        return -1;
    }
    char buffer[1024];
    for (int ii = 0;ii < 3;ii++)
    {
        int iret;
        memset(buffer,0,sizeof(buffer));
        sprintf(buffer,"this is %dth work day",ii+1);
        if (( iret = send(sockfd,buffer,strlen(buffer),0)) <= 0)
        {
            perror("send");
            break;
        }
        memset(buffer,0,sizeof(buffer));
        if ( (iret = recv(sockfd,buffer,sizeof(buffer),0)) <= 0)
        {
            printf("NO.%d send failed!\n",ii+1);
            break;
        }
        printf("receive %s\n",buffer);

    }
    close(sockfd);
    return 0;
}

